package com.pine.service.pineframework.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysMenuQueryRequest;
import com.pine.common.beans.pineframework.response.SysMenuQueryResponse;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.beans.response.DropDownTreeResponse;
import com.pine.common.beans.response.PageResponse;
import com.pine.dao.pineframework.constants.VisibleEnum;
import com.pine.dao.pineframework.entity.SysMenu;
import com.pine.manager.pineframework.SysMenuManager;
import com.pine.manager.pineframework.bo.SysMenuBo;
import com.pine.manager.pineframework.convertors.SysMenuConvertor;
import com.pine.manager.pineframework.query.SysMenuQuery;
import com.pine.service.pineframework.SysMenuService;
import com.pine.service.util.PageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-12
 */
@Slf4j
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Resource
    private SysMenuManager sysMenuManager;

    @Resource
    private SysMenuConvertor sysMenuConvertor;

    private static final Map<String, SFunction<SysMenu, ?>> COLUMNS_FUNCTION_MAP;

    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", SysMenu::getId
        );
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public SysMenuQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        SysMenuBo sysMenuBo = sysMenuManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, SysMenu::getId));
        return sysMenuConvertor.entityBoToQueryResponse(sysMenuBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<SysMenuQueryResponse> list(SysMenuQueryRequest request) {
        SysMenuQuery sysMenuQuery = sysMenuConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(sysMenuQuery)) {
            List<SysMenuBo> sysMenuList = sysMenuManager.list(sysMenuQuery);
            if (ObjectUtils.isNotEmpty(sysMenuList)) {
                return sysMenuList.stream()
                        .map(sysMenuConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<SysMenuQueryResponse> listPages(PageRequest<SysMenuQueryRequest> request) {
        try {
            // 分页查询
            IPage<SysMenuBo> sysMenuPage = sysMenuManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(sysMenuPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param sysMenuPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<SysMenuQueryResponse> safelyConvertPage(IPage<SysMenuBo> sysMenuPage) {
        if (sysMenuPage == null || sysMenuPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<SysMenuQueryResponse> responses = sysMenuPage.getRecords().parallelStream()
                .map(sysMenuBo -> sysMenuConvertor.entityBoToQueryResponse(sysMenuBo))
                .collect(Collectors.toList());

        return PageUtil.convertPage(sysMenuPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<SysMenuQuery> transformToQuery(PageRequest<SysMenuQueryRequest> request) {
        SysMenuQuery sysMenuQuery = sysMenuConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), sysMenuQuery);
    }

    /**
     * 查询菜单及子菜单
     *
     * @param menuId 顶层菜单ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> listMenuAndChild(Long menuId) {
        // 递归查询菜单和子菜单
        return sysMenuManager.getMapper().listMenuAndChild(menuId);
    }

    /**
     * 下拉选择，查询菜单树形结构
     *
     * @return 菜单树形结构
     */
    @Override
    public List<DropDownTreeResponse<Long>> dropDownTree() {
        // 查询显示中的全部菜单
        SysMenuQuery sysMenuQuery = new SysMenuQuery();
        sysMenuQuery.setVisible(VisibleEnum.SHOW);
        List<SysMenuBo> sysMenuList = sysMenuManager.list(sysMenuQuery);
        if (ObjectUtil.isEmpty(sysMenuList)) {
            return Collections.emptyList();
        }

        // 转换结构
        return sysMenuList.stream()
                .map(sysMenu -> {
                    DropDownTreeResponse<Long> dropDownTreeResponse = new DropDownTreeResponse<>();
                    dropDownTreeResponse.setValue(sysMenu.getId());
                    dropDownTreeResponse.setLabel(sysMenu.getName());
                    dropDownTreeResponse.setParentId(sysMenu.getParentId());
                    dropDownTreeResponse.setWeight(sysMenu.getSort());
                    return dropDownTreeResponse;
                }).toList();
    }
}
